<?php
require_once 'Zend/Gdata.php';
require_once 'Zend/Gdata/Query.php';
require_once 'Zend/Http/Client.php';

require_once 'Oos/Site.php';
require_once 'Oos/Search.php';
require_once 'Oos/Site/SiteQuery.php';
require_once 'Oos/Site/SiteEntry.php';
require_once 'Oos/Auth/AuthWSSE.php';

class Oos
{
	protected $_mode;
	protected $_user_slug;
	protected $_client;
	protected $_entrypoint;
	protected $_apiKey;
	protected $_apiSecret;
	protected $_authSign;

	private function setInfoFromService() 
	{
		preg_match_all('/<collection href="([^"]+)"/iU', $this->_client->getLastResponse()->getBody(), $matches);
		
		if (strlen($matches[0][0])) 
		{
			$euri = explode("/", $matches[1][0]);
			$this->_user_slug = array_pop($euri);
		}
	}

	public function setCredentials($user, $password) 
	{
		$clientp = new Zend_Http_Client();
		$this->_client = Oos_WSSE_Login::getHttpClient($user, $password, $clientp);
		$this->setInfoFromService();  	
		$this->_mode = "authenticated";
	}

	public function setApiKey($apiKey, $apiSecret) 
	{
		$this->_mode = "anonymous";
		$this->_apiKey = $apiKey;
		$this->_apiSecret = $apiSecret;
		$this->_authSign = md5($apiKey . $apiSecret);
		$clientp = new Zend_Http_Client();
		$this->_client = $clientp;
	}

	public function __construct($entrypoint = null)
	{
		if ($entrypoint == null)
		{
			$this->_entrypoint = 'http://11870.com/api/v1';
		} else {
			$this->_entrypoint = $entrypoint;
		}
	}


	public function getUser() 
	{
		return;
	}

	public function sites() 
	{
		$gdata = new Oos_Site($this->_client, $this->_entrypoint, $this->_user_slug, $this->_apiKey, $this->_apiSecret);
		return $gdata;
	}

	public function contacts()
	{
		$gdata = new Oos_Contact($this->_client);
		return $gdata;
	}

	public function search($query) 
	{		
		$search = new Oos_Search($this->_client, $this->_entrypoint, $this->_apiKey, $this->_apiSecret);
		$gdata = $search->getResults($query);
		return $gdata;
	}
	
	public function generateSearchQuery()
	{
		$q = new Oos_Site_SiteQuery($this->_entrypoint);
		$q->setApiKey($this->_apiKey);
		$q->setAuthSign($this->_authSign);
		
		return $q;
	}
}

?>
